package vn.edu.fpt.xml.back.daos;

import org.springframework.stereotype.Repository;
import vn.edu.fpt.xml.back.entities.ArticleEntity;

import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.List;

/**
 * Created by hiephn on 2014/04/27.
 */
@Repository
public class ArticleDao extends GenericJpaDao<ArticleEntity> {

    private static final String FROM_ARTICLE_ENTITY = "FROM " + ArticleEntity.class.getName();
    private static final String FIND_BY_TITLE_AND_PUBIC_DATE = FROM_ARTICLE_ENTITY + " WHERE title = :title AND publicDate = :publicDate";
    private static final String FIND_ARTICLE_ON_HOMEPAGE = FROM_ARTICLE_ENTITY + " WHERE onHomePage = 1 ORDER BY channelId";
    private static final String FIND_BY_RELATIVE_ORIGIN_URL = FROM_ARTICLE_ENTITY + " WHERE originUrl like :originUrl";
    private static final String DELETE_ALL = "DELETE " + FROM_ARTICLE_ENTITY;

    public ArticleEntity findByTitleAndPubicDate(String title, Timestamp publicDate) {
        Query query = entityManager.createQuery(FIND_BY_TITLE_AND_PUBIC_DATE);
        query.setParameter("title", title);
        query.setParameter("publicDate", publicDate);
        return executeSingle(query);
    }

    public List<ArticleEntity> findArticleOnHomePage() {
        Query query = entityManager.createQuery(FIND_ARTICLE_ON_HOMEPAGE);
        return executeList(query);
    }

    public ArticleEntity findArticleByRelativeOriginUrl(String relativeOriginUrl) {
        Query query = entityManager.createQuery(FIND_BY_RELATIVE_ORIGIN_URL);
        query.setParameter("originUrl", "%" + relativeOriginUrl);
        return executeSingle(query);
    }

    public int deleteAll() {
        Query query = entityManager.createQuery(DELETE_ALL);
        return query.executeUpdate();
    }
}
